package cc.laop.utils;

import org.apache.commons.codec.digest.DigestUtils;

public class PasswordDigestUtil {

    public static String md5Digest(String str) {
        if (str != null) {
            String passwordDigest = DigestUtils.md5Hex(str.getBytes());
            return passwordDigest;
        }
        return null;
    }

    public static boolean checkMd5Digest(String password, String digest) {
        if (password != null) {
            String passwordDigest = DigestUtils.md5Hex(password
                    .getBytes());
            String newPasswordDigest = PasswordDigestUtil
                    .separateSolt(password, digest);
            return passwordDigest.equalsIgnoreCase(newPasswordDigest);
        }
        return false;
    }

    private static String soltDigest() {
        String solt = RandomUtil.randomCode(8);
        return DigestUtils.md5Hex(solt.getBytes());
    }

    public static String md5DigestMixSolt(String password) {
        String soltDigest = PasswordDigestUtil.soltDigest();
        int pdHashcode = password.hashCode();
        int index = pdHashcode % 32;
        index = Math.abs(index);
        String passwordDigest = PasswordDigestUtil.md5Digest(password);
        StringBuffer buffer = new StringBuffer(passwordDigest);
        buffer.insert(index, soltDigest);
        return buffer.toString();
    }

    public static String separateSolt(String password, String digest) {
        int pdHashcode = password.hashCode();
        int index = pdHashcode % 32;
        index = Math.abs(index);
        String newPasswordDigest = digest.substring(0, index)
                + digest.substring(index + 32);
        return newPasswordDigest;
    }

}
